<template>
  <a-modal title="修改生产计划" v-model:visible="visible" :width="800">
    <template #footer>
      <a-space>
        <a-button @click="visible = false">取消</a-button>
        <a-button @click="handleOk" type="primary">确认</a-button>
      </a-space>
    </template>
    <a-spin :loading="isLoading">
      <a-form auto-label-width :model="formData" ref="refForm" class="form">
        <a-row :gutter="15">
          <a-col :span="8">
            <a-form-item label="生产计划编号">
              <a-input
                placeholder="无需输入，系统自动生成..."
                disabled
                v-model="formData.code"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="计划类型" field="type">
              <a-select placeholder="计划类型" v-model="formData.type" disabled>
                <a-option :value="1">周计划</a-option>
                <a-option :value="2">月计划</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :label="formData.type == 1 ? '选择周' : '选择月'"
              v-if="!!formData.type"
              field="startDate"
            >
              <a-month-picker
                v-model="formData.startDate"
                value-format="Date"
                disabled
                v-if="formData.type == 2"
              />
              <a-week-picker
                v-model="formData.startDate"
                value-format="Date"
                disabled
                :day-start-of-week="1"
                v-else
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item field="capacity" label="日标准产能:">
              <a-input-number
                :min="1"
                disabled
                v-model="formData.capacity"
                placeholder="输入日标准产能"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8" v-if="formData.type === 2">
            <a-form-item label="计划总数:">
              {{ getTotal() }}
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <Calendar ref="refCalendar">
        <template #day="{ millisecond, dateJs }">
          <a-input-number
            :min="1"
            :max="formData.capacity"
            :disabled="isDisabled(dateJs) || !!isSchedulingList[millisecond]"
            v-model="dateListForm[millisecond]"
            :placeholder="!isDisabled(dateJs) ? '输入排程数量' : ''"
          />

          <template v-if="!isDisabled(dateJs)">
            <a-typography-text
              type="primary"
              v-if="!!isSchedulingList[millisecond + '']"
            >
              已转车间计划
            </a-typography-text>
            <a-typography-text
              type="success"
              v-else-if="dateListForm[millisecond]"
            >
              未转车间计划
            </a-typography-text>
          </template>
        </template>
      </Calendar>
    </a-spin>
  </a-modal>
</template>

<script setup lang="ts">
  import { reactive, onMounted, ref, computed, watch } from 'vue';
  import { TPlanProduction } from '@/api/produce-management/OrderPlanning/type';
  import { EditProducePlan } from '@/api/produce-management/OrderPlanning';
  import dayjs from 'dayjs';
  import { Message } from '@arco-design/web-vue';

  let formData = reactive<TPlanProduction>({});
  let isLoading = ref(false);
  let dateListForm = reactive<any>({});
  let isSchedulingList = reactive<any>({});

  let regionList = computed(() => {
    let { startDate, type } = formData;
    if (!startDate || !type) return false;
    let nowDate = dayjs(startDate);
    let startDateJs;
    let endDateJs;
    if (type === 2) {
      startDateJs = dayjs(startDate).startOf('M');
      if (startDateJs.isSame(nowDate, 'month')) startDateJs = nowDate;
      endDateJs = startDateJs.endOf('M').startOf('D');
    } else {
      startDateJs = dayjs(startDate).startOf('w').add(1, 'day');
      endDateJs = startDateJs.endOf('w').add(1, 'day').startOf('D');
      if (nowDate.isAfter(startDateJs) && nowDate.isBefore(endDateJs)) {
        startDateJs = nowDate;
      }
    }
    if (endDateJs.isBefore(nowDate)) return false;
    return [startDateJs.subtract(1, 'day'), endDateJs.add(1, 'day')];
  });

  let isDisabled = (dateJs: any) => {
    if (!regionList.value) return true;
    let [start, end] = regionList.value;
    if (dateJs.isAfter(start)) return false;
    return true;
  };
  let getTotal = () => {
    let num = 0;
    for (const key in dateListForm) {
      num += Number(dateListForm[key]);
    }
    return num;
  };
  let visible = ref(false);
  let setData = (data: TPlanProduction) => {
    Object.assign(formData, data);
    formData.startDate = new Date(data.startDate + '');
    data.data?.forEach(({ date, number, isScheduling }) => {
      dateListForm[dayjs(new Date(date)).valueOf()] = number;
      isSchedulingList[dayjs(new Date(date)).valueOf()] = isScheduling;
    });
    visible.value = true;
  };
  let emit = defineEmits(['ok']);
  let handleOk = async () => {
    // isLoading.value = true;
    let list = [];
    for (const key in dateListForm) {
      let num = dateListForm[key];
      if (num)
        list.push({
          date: dayjs(Number(key)).toJSON(),
          number: num,
          isScheduling: isSchedulingList[key] ? 0 : 0,
        });
    }
    let totalNum = list.reduce(
      (num, { number }) => (number ? num + number : num),
      0
    );
    if (totalNum > (formData.produceNumber as number)) {
      //
      return Message.error('生成计划数量大于工单数量');
    }
    await EditProducePlan({
      ...formData,
      startDate: dayjs(formData.startDate).toJSON(),
      data: list,
      totalNum: list.reduce(
        (num, { number }) => (number ? num + number : num),
        0
      ),
    });
    emit('ok');
    visible.value = false;
    isLoading.value = false;
  };
  let resettingDateListForm = () => {
    for (const key in dateListForm) {
      delete dateListForm[key];
    }
    for (const key in isSchedulingList) {
      delete isSchedulingList[key];
    }
    for (const key in formData) {
      delete formData[key];
    }
  };
  watch(visible, () => {
    if (!visible.value) resettingDateListForm();
  });
  defineExpose({ setData });
  let getRules = (name?: string) => {
    return [{ required: true, message: (name || '') + '不能为空' }];
  };
</script>

<style scoped></style>
